package com.example.children.yyz;

import com.example.children.Util.UUIDGenerator;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class TAListService {
    private List<TechnicalAchievement> achievements = new ArrayList<>();
    // 构造函数，创建并添加技术成果
    public TAListService() {
        // 创建几个 TechnicalAchievement 对象
        TechnicalAchievement achievement1 = new TechnicalAchievement(
                "1", "人工智能在医疗中的应用", "人工智能", "一个用于疾病诊断的人工智能系统。",
                "确保数据隐私。", "改善患者的治疗效果。", "错误风险低。"
        );

        TechnicalAchievement achievement2 = new TechnicalAchievement(
                "2", "量子计算", "物理学", "量子计算算法的突破性进展。",
                "可能带来伦理困境。", "将改变科技领域。", "因未经过充分验证，存在较高风险。"
        );

        // 将对象添加到列表中
        achievements.add(achievement1);
        achievements.add(achievement2);
    }


    // 创建（Create）
    public void addAchievement(TechnicalAchievement achievement) {
        String uuid= UUIDGenerator.generateNumericUUID(8);
        achievement.setId(uuid);
        achievements.add(achievement);
        clearFile(BYTE_FILE_PATH);   //清除文件内容
        saveListToByteFile(achievements);   //字节流持久化：将 List<TechnicalAchievement> 写入文件

    }

    // 读取（Read）- 根据ID查询
    public TechnicalAchievement getAchievementById(String id) {
        for (TechnicalAchievement achievement : achievements) {
            if (achievement.getId().equals(id)) {
                return achievement;
            }
        }
        return null;
    }

    // 更新（Update）
    public void updateAchievement(String id, TechnicalAchievement updatedAchievement) {
        for (int i = 0; i < achievements.size(); i++) {
            if (achievements.get(i).getId().equals(id)) {
                achievements.set(i, updatedAchievement);
                return;
            }
        }
        clearFile(BYTE_FILE_PATH);   //清除文件内容
        saveListToByteFile(achievements);   //字节流持久化：将 List<TechnicalAchievement> 写入文件
    }

    // 删除（Delete）
    public void deleteAchievement(String id) {
        achievements.removeIf(achievement -> achievement.getId().equals(id));
        clearFile(BYTE_FILE_PATH);   //清除文件内容
        saveListToByteFile(achievements);   //字节流持久化：将 List<TechnicalAchievement> 写入文件
    }

    //返回集合
    public List<TechnicalAchievement> getAchievements() {
        saveListToByteFile( achievements);  //字节，写入
        List<TechnicalAchievement> test=readListFromByteFile();
        System.out.println("文件中的集合内容如下：（字节）：");
        for (TechnicalAchievement achievement : test) {
            System.out.println("id: " + achievement.getId());
            System.out.println("name: " + achievement.getName());
            System.out.println("所属领域: " + achievement.getField());
            System.out.println("成果描述: " + achievement.getDescription());
            System.out.println("伦理考量: " + achievement.getEthicsConsiderations());
            System.out.println("社会影响: " + achievement.getSocialImpact());
            System.out.println("风险评估: " + achievement.getRiskAssessment());
            System.out.println("------");
        }
        return achievements;
//        return  test;
    }


    //实验IO流
    // 文件路径
    private static final String BYTE_FILE_PATH = "D:/java_spring-boot/Children/src/main/java/com/example/children/yyz/io/achievements.txt";   // 存储字节流的文件
    private static final String OBJECT_FILE_PATH = "com.example.children.yyz.io.achievements.obj"; // 存储对象流的文件


    //清除文件内容
    public static void clearFile(String filePath) {
        try (FileOutputStream fos = new FileOutputStream(filePath)) {
            // 什么都不写，只是打开文件并清空内容
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("清空文件失败: " + filePath);
        }
    }


    // 字节流持久化：将 List<TechnicalAchievement> 写入文件
    public void saveListToByteFile(List<TechnicalAchievement> achievements) {
        System.out.println("字节流持久化：从文件中读取 List<TechnicalAchievement>");
        try (FileOutputStream fileOutputStream = new FileOutputStream(BYTE_FILE_PATH);
             BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream)) {

            ObjectOutputStream objectOutputStream = new ObjectOutputStream(bufferedOutputStream);
            objectOutputStream.writeObject(achievements);
            System.out.println("数据已通过字节流保存到文件");
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("字节流数据持久化失败："+e);
        }
    }

    // 字节流持久化：从文件中读取 List<TechnicalAchievement>
    public List<TechnicalAchievement> readListFromByteFile() {
        System.out.println("字节流持久化：从文件中读取 List<TechnicalAchievement>");
        try (FileInputStream fileInputStream = new FileInputStream(BYTE_FILE_PATH);
             BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream)) {

            ObjectInputStream objectInputStream = new ObjectInputStream(bufferedInputStream);
            return (List<TechnicalAchievement>) objectInputStream.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            System.err.println("从字节流文件读取数据失败");
            return null;
        }
    }



    // 对象流持久化：将 List<TechnicalAchievement> 写入文件
    public void saveListToObjectFile(List<TechnicalAchievement> achievements) {
        System.out.println("对象流持久化：将 List<TechnicalAchievement> 写入文件");
        try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(OBJECT_FILE_PATH))) {
            objectOutputStream.writeObject(achievements);
            System.out.println("数据已通过对象流保存到文件");
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("对象流数据持久化失败");
        }
    }

    // 对象流持久化：从文件中读取 List<TechnicalAchievement>
    public List<TechnicalAchievement> readListFromObjectFile() {
        System.out.println("对象流持久化：从文件中读取 List<TechnicalAchievement>");
        try (ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(OBJECT_FILE_PATH))) {
            return (List<TechnicalAchievement>) objectInputStream.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            System.err.println("从对象流文件读取数据失败");
            return null;
        }
    }












}

